package com.garen.common;

import java.io.*;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.garen.utils.FileUtils;

/*
 * 负责与前台交互
 * */
public abstract class AbstractAction {
 
	protected static Log log = LogFactory.getLog(AbstractAction.class);
	//mime常量
	final protected static String HTTP_MIME_TYPE_JPEG = "image/jpeg";
	final protected static String HTTP_MIME_TYPE_GIF = "image/gif";
	final protected static String HTTP_MIME_TYPE_PNG = "image/png";
	final protected static String HTTP_MIME_TYPE_JSON = "application/json; charset=utf-8";
	final protected static String HTTP_MIME_TYPE_XLS = "application/vnd.ms-excel";
	final protected static String HTTP_MIME_TYPE_WORD = "application/vnd.ms-word";
	final protected static String HTTP_MIME_TYPE_PDF = "application/pdf";
	final protected static String HTTP_MIME_TYPE_APK = "application/apk";
	final protected static String HTTP_MIME_TYPE_HTML = "text/html; charset=utf-8";
	final protected static String HTTP_MIME_TYPE_JS = "application/javascript";
	final protected static String HTTP_MIME_TYPE_CSS = "text/css";
	final protected static String HTTP_MIME_TYPE_WAVE = "audio/x-wav";
	//json解析对象
	public static JSONObject getJSONObject(JSONObject jobj,String key) {
		if(jobj == null || key == null) return null;
		try{
			return jobj.getJSONObject(key);
		}catch(Exception ex){}
		return null;
	}
		
		
	//json序列化,防止循环引用
	public static String toJSON(Object obj){
		return JSON.toJSONString(obj,
				SerializerFeature.DisableCircularReferenceDetect);
	}
	
	//获取客户端IP
	protected String getClientIp() {
		return AbstractFilter.getRequest().getRemoteAddr();
	}
		
	//获取默认图片
	private static byte [] getDefaultPic(){
		String path = "images/nophoto.gif";
		path = AbstractFilter.getSession().getServletContext().getRealPath(path);
		return FileUtils.readData(path);
	}
	
	//下载图片
	public static ModelAndView downPic(byte [] bpic) {
		if(bpic == null) bpic = getDefaultPic();
		responseStream(AbstractFilter.getResponse(),bpic,HTTP_MIME_TYPE_JPEG);
		return null;
	}
		
	//下载xls文档
	public static ModelAndView downXlsFile(File file,String fileName) {
		HttpServletResponse response =  AbstractFilter.getResponse();
		try {
			response.addHeader("Content-Disposition", "attachment;filename=" 
					+ fileName);
			responseStream(response,FileUtils.readbodydata(new FileInputStream(file), 0),//读取文件字节流
					HTTP_MIME_TYPE_XLS);
		} catch (FileNotFoundException e1) {
			//e1.printStackTrace();
		}
		return null;
	}
		
	//下载xls文档
	protected  ModelAndView downPdfFile(File file,String fileName) {
		HttpServletResponse response =  AbstractFilter.getResponse();
		try {
			response.addHeader("Content-Disposition", "attachment;filename=" 
					+ fileName);
			responseStream(response,FileUtils.readbodydata(new FileInputStream(file), 0),//读取文件字节流
					HTTP_MIME_TYPE_PDF);
		} catch (FileNotFoundException e1) {
			//e1.printStackTrace();
		}
		return null;
	}
		
	//返回json格式
	public static ModelAndView downCss(byte[] bcss){
		responseStream(AbstractFilter.getResponse(),bcss,HTTP_MIME_TYPE_CSS);
		return null;
	}
		
	/*
	 * 另存为...
	 * 参数:
	 * 	body资源流
	 *  type content-type
	 *  fileName 文件名称
	 * */
	public static ModelAndView downFile(byte[] body,String type,String fileName){
		HttpServletResponse response =  AbstractFilter.getResponse();
		HttpServletRequest request =  AbstractFilter.getRequest();
		String userAgent = request.getHeader("User-Agent");
		try{
			if(BrowserType.isFirefox(userAgent)){
				fileName = new String(fileName.getBytes("utf-8"),"iso-8859-1");
			}else {
				fileName = URLEncoder.encode(fileName,"utf-8");
			}
		}catch(UnsupportedEncodingException ex){}
		if(StringUtils.isNotEmpty(fileName)){
			response.addHeader("Content-Disposition", "attachment;filename=" 
					+ fileName);
		}
		if(StringUtils.isNotEmpty(type)){
			type = HTTP_MIME_TYPE_HTML;
		}
		responseStream(AbstractFilter.getResponse(),body,type);
		return null;
	}
		
	//返回json格式
	public static ModelAndView downJs(byte[] bjs){
		responseStream(AbstractFilter.getResponse(),bjs,HTTP_MIME_TYPE_JS);
		return null;
	}
		
	//返回json格式
	public static ModelAndView downWav(byte[] body){
		responseStream(AbstractFilter.getResponse(),body,HTTP_MIME_TYPE_WAVE);
		return null;
	}
		
	//返回字符串到前台
	protected static ModelAndView Html(String html){
		try {
			responseStream(AbstractFilter.getResponse(),
					html.getBytes("utf-8"),HTTP_MIME_TYPE_HTML);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
		
	//返回json格式
	public static ModelAndView Json(Object obj){
		try {
			String json_str = toJSON(obj);
			responseStream(AbstractFilter.getResponse(),
					json_str.getBytes("utf-8"),HTTP_MIME_TYPE_JSON);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//输出流到客户端
	protected static void responseStream(HttpServletResponse response,
			byte [] bpost,String type){
		try {
			response.setContentType(type);
			if(bpost == null) bpost = new byte[0];
			response.setContentLength(bpost.length);
			OutputStream outs = response.getOutputStream();
			outs.write(bpost);
			outs.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
